package com.jfm.jfmm.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author DYang
 * @since 2024-10-19 23:33
 */
public class SHA256Util {

    /**
     * 获取SHA256加密后的字符串，默认编码为UTF-8，输出长度为固定10位，输出为数字字符串
     */
    public static String getSHA256Str(String input,int length) {
        try {
            // 获取MessageDigest实例，指定使用SHA-256算法
            MessageDigest md = MessageDigest.getInstance("SHA-256");

            // 计算输入字符串的哈希值
            byte[] hashBytes = md.digest(input.getBytes());

            // 将字节数组转换为十六进制字符串
            StringBuilder hexString = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }

            // 将十六进制字符串转换为数字字符串
            BigInteger decimalValue = new BigInteger(hexString.toString(), 16);

            // 将数字字符串格式化为固定长度
            long res = decimalValue.intValue() % (long) Math.pow(10, length);
            res = res < 0 ? - res : res;
            return String.format("%0" + length + "d", res);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("无法找到SHA-256算法", e);
        }
    }
}
